﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Engine.Messaging.Listener;
using Engine.Messaging.Messages;
using log4net;
using Engine.Base;

namespace Engine.Messaging
{
    public class MessageSystem : ISubSystem
    {
        #region Constructors
        public MessageSystem() { }
        #endregion // Constructors


        #region Methods
        public void Broadcast<T>(object sender, T m) where T : Message
        {
            Logger.Debug(String.Format("Broadcasting message from sender {0}:\n{1}", sender, m));
            MessageListenersHandle<T>.Instance.Raise(sender, m);
        }

        public void Subscribe<T>(IMessageListener<T> listener) where T : Message
        {
            Logger.Debug(String.Format("Listener subscribed for type {0}", typeof(T)));
            MessageListenersHandle<T>.Instance.Add(listener);
        }
        public void Unsubscribe<T>(IMessageListener<T> listener) where T : Message
        {
            Logger.Debug(String.Format("Listener unsubscribed for type {0}", typeof(T)));
            MessageListenersHandle<T>.Instance.Remove(listener);
        }
        #endregion // Methods


        #region ISubSystem-Implementation
        public void Start()
        {
            Logger.Debug("Starting MessageSystem");
        }

        public void Stop()
        {
            Logger.Debug("Stoping MessageSystem");
        }
        #endregion // ISubSystem-Implementation


        #region STATIC
        private static ILog Logger { get; set; }
        static MessageSystem()
        {
            Logger = LogManager.GetLogger(typeof(MessageSystem));
        }
        #endregion // STATIC
    }
}
